package cn.easy.mortgage.service;

import cn.easy.mobile.utils.Constants;
import cn.easy.mobile.utils.MobileUtil;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springside.modules.utils.mapper.JsonMapper;
import org.springside.modules.utils.text.TextValidator;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class LvXinTongSmsService {
    protected org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${sms.app_username}")
    private String APP_USERNAME = "app_username";
    @Value("${sms.app_password}")
    private String APP_PASSWORD = "app_password";
    @Value("${sms.app_url}")
    private String APP_URL = "app_url";
    @Value("${sms.app_sign_name}")
    private String SIGN_NAME = "app_sign_name";

    public String getSPName() {
        return "LvXinTong";
    }

    public void sendCode(Map<String, Object> pool, String mobile, String noticeTemplate) throws IOException, TemplateException {
        // 验证码
        String code = RandomStringUtils.random(6, false, true);
        // 注册验证码模版
        Map<String, Object> sendData = new HashMap<String, Object>();
        // 获取 注册验证码 短信模版内容
        sendData.put("code", code);
        // 发送短信方法
        Boolean sent = send(mobile, MobileUtil.renderTemplate(noticeTemplate, sendData));
        if (sent) {
            Map varPool = (Map) pool.get(mobile);
            if (varPool == null) {
                varPool = new HashMap<String, Object>();
                varPool.put(Constants.CODE_GET_COUNT, 1);
                varPool.put(Constants.VERIFICATION_CODE, code);
                varPool.put(Constants.ADD_TIME, new Date().getTime());
            } else {
                Integer codeCount = (int) varPool.get(Constants.CODE_GET_COUNT);
                codeCount++;
                varPool.put(Constants.VERIFICATION_CODE, code);
                varPool.put(Constants.ADD_TIME, new Date().getTime());
                varPool.put(Constants.CODE_GET_COUNT, codeCount);
            }
            pool.put(mobile, varPool);
        }
    }

    private Boolean send(String phone, String content) {
        if (!TextValidator.isMobileSimple(phone)) {
            logger.error("短信提交失败：mobile=" + phone + ",signName=" + SIGN_NAME + " ,msg=手机号码格式不正确");
            return false;
        }
        JsonMapper jsonMapper = JsonMapper.defaultMapper();

        Map<String, String> map = new HashMap<>();
        map.put("name", APP_USERNAME);
        map.put("pswd", APP_PASSWORD);
        map.put("mobile", phone);
        map.put("msg", content);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(APP_URL);
        List<NameValuePair> params = new ArrayList<>();
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String name = it.next();
            params.add(new BasicNameValuePair(name, map.get(name)));
        }
        Boolean result = null;
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            Map responseMap = jsonMapper.fromJson(responseString, Map.class);
            if (responseMap != null && (int) responseMap.get("respstatus") == 0) {
                result = true;
                logger.info("短信提交成功：mobile=" + phone + ",content=" + content + ",signName=" + SIGN_NAME + ",msg=" + responseString);
            } else {
                logger.error("短信提交失败：mobile=" + phone + ",content=" + content + ",signName=" + SIGN_NAME + ",status=" + responseMap.get("respstatus"));
                return false;
            }
            return result;
        } catch (IOException e) {
            logger.error("发送短信异常：", e);
            return false;
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error("发送短信异常：", e);
                return false;
            }
        }
    }

    public String getSmsSign() {
        if (SIGN_NAME != null) {
            return SIGN_NAME;
        }
        return "";
    }
}
